import { Breadcrumb } from 'antd';
import { Link, useLocation } from 'react-router-dom';
import { useEffect, useState } from 'react';
import routerData from 'src/router/routerData';

const routerAy = (routerData && routerData()) || [];
function JBreadcrumb(props) {
  const [list, setList] = useState([]);

  const location = useLocation();
  const { pathname } = location;

  useEffect(() => {
    function genList(routes, data, prefix = '') {
      /**
       * 组合面包屑列表
       * */
      if (!routes) {
        return;
      }
      const pathAy = pathname.replace('/', '').split('/');
      pathAy.forEach((v) => {
        const findRoute = routes.find((route) => v === route.path);
        if (findRoute) {
          const item = {
            url: `${prefix}/${findRoute.path}`,
            title: findRoute.meta?.title || '',
          };
          if (findRoute.element || findRoute.isElement) {
            item.isUrl = true;
          }
          data.push(item);
          genList(findRoute.children, data, item.url);
        }
      });
    }

    const tempList = [];
    genList(routerAy, tempList, '');
    setList(tempList);
  }, [pathname]);

  return (
    <div className={props.className}>
      <Breadcrumb {...props}>
        {list.map((item) => (
          <Breadcrumb.Item key={item.url}>
            {item.isUrl ? <Link to={item.url}>{item.title}</Link> : item.title}
          </Breadcrumb.Item>
        ))}
      </Breadcrumb>
    </div>
  );
}

export default JBreadcrumb;
